package edu.whu.notepal.controller;

import edu.whu.notepal.dto.Result;
import edu.whu.notepal.pojo.Group;
import edu.whu.notepal.pojo.User;
import edu.whu.notepal.service.SubscriberService;
import edu.whu.notepal.service.UserService;
import edu.whu.notepal.utils.MessageType;
import edu.whu.notepal.utils.MyWebSocket;
import edu.whu.notepal.utils.SocketBeanFactory;
import edu.whu.notepal.utils.UserHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 群成员的控制器方法
 * @author 陈磊
 */
@RestController
@RequestMapping("/subscriber")
public class SubscriberController {

    @Resource
    SubscriberService subscriberService;

    @Resource
    MyWebSocket myWebSocket;

    @Resource
    UserService userService;

    @PostMapping
    public Result<String> addGroup(Long noteId){
        Long userId = UserHolder.getUser().getId();
        subscriberService.addGroup(userId,noteId);
        myWebSocket.sendGroupMessage(SocketBeanFactory.
                groupInstance(userId,null, MessageType.SOMEONE_ENTER,userService.getById(userId).getName()+"加入群组",noteId,noteId));
        return Result.success("加入群组成功！");
    }

    @DeleteMapping
    public Result<String> exitGroup(Long noteId){
        Long userId = UserHolder.getUser().getId();
        subscriberService.exitGroup(userId,noteId);
        myWebSocket.sendGroupMessage(SocketBeanFactory.
                groupInstance(userId,null, MessageType.SOMEONE_EXIT,userService.getById(userId).getName()+"退出群组",noteId,noteId));
        return Result.success("退出群组成功！");
    }

    @DeleteMapping("/kick")
    public Result<String> kick(Long noteId,Long userId){
        subscriberService.exitGroup(userId,noteId);
        myWebSocket.sendToOne(SocketBeanFactory.
                groupInstance(userId,userId, MessageType.GET_BOOTED,"您已被移出群聊"+noteId,noteId,noteId));
        return Result.success("操作成功！");
    }


    @GetMapping("/all")
    public Result<List<User>>getAllSubscribers(Long noteId){
        return Result.success(subscriberService.getSubscribersId(noteId)
                .stream()
                .map(userService::getById)
                .collect(Collectors.toList()));
    }

    @GetMapping("/allGroups")
    public Result<List<Group>>getAllGroup(){
        return Result.success(subscriberService.getGroups(UserHolder.getUser().getId()));
    }

}